/*bin/true;exec rexx "$0" "$@";exit # REXX */

logfile = "/data/dackelrun.log"

/* command line:  
		dackelrunn.rexx [<num>] [<dackel arguments>]
   
   if <num> is given then <num> measurements will be performed
   <dackel arguments> are passed on to dackel 
*/
parse value arg(1) with runs dackelopts
if (datatype(runs) \= "NUM") then do
	/* <num> not given, so we'll loop forever */
	runs = -1
	runcounter = 55555;
	dackelopts = arg(1)
end
else do
	runcounter = runs;
end

call stream logfile, "c", "open"
call lineout logfile, date('O') time('N') "dackelrun.rexx" arg(1)
call stream logfile, "c", "close"

/* dackel should write its output to a subdirectory of /data corresponding to the current data,
   a run is always stored in a single directory
*/
outdir = "/data/" || date("S")
if (\fileexists(outdir)) then
	"mkdirhier" outdir

/* loop over number <num> of runs
*/
do while (runcounter > 0)

	/* determine next czcle number
	*/
	cycle = nextcycle()
	
	/* build output filenames
	*/
	cycle = copies('0', 6-length(cycle)) || cycle
	rootfile = outdir"/data"cycle".root"
	logfile = outdir"/data"cycle".log"

	/* call dackel 
	*/
	cmdline = "./dackel -t 10 -S 10010110 -r 4 -o" rootfile "-l" logfile dackelopts
	call stream logfile, "c", "open"
	call lineout logfile, date('O') time('N') "counter:" runcounter "command:" cmdline
	call stream logfile, "c", "close"
	say cmdline
	cmdline
	
	/* change permissions of output files */
	/* TODO: also change owner! */
	/* TODO: reactivate this once we got a reasonable return value from dackel, which indicates success status */
	/*       (or let dackel do that) */
	/* "chmod ugo-w" rootfile logfile */
		
	/* decrease runcounter, if we do not run forever */
	if (runs > 0) then
		runcounter = runcounter - 1
		
	/* wait shortly, so that the user can interrupt via keyboard */
	if (runcounter > 1) then
		call SysSleep 1
end
return 0

/* the next cycle's number is stored in cycle.count */
nextcycle: procedure
	f = "/data/cycle.count"
	call stream f, "c", "open read"
	cycle = linein(f)
	call stream f, "c", "close"
	return cycle

/* determine if a file/directory actually exists, returns true/false */
fileexists:
	return stream(arg(1), "c", "query exists") \= ""

